<template>
  <!--预览JSON数据的列表！-->
  <my-list

      ref="list"
      :currentPage.sync="$data.pageNumber"
      :page-size="15"
      :store="true"
      :model-value="$data.previewData"
      @row-dblclick="row_click"
      @param="p=>$emit('pager-change',p)"
      noQueryPart
      noIndexColumn
  >
    <el-table-column type="index" align="center" width="60" class-name="el-cell-index">
      <template #header="scope">
        <el-button type="primary"
                   :icon="View"
                   @click="view_open_click" size="small"
                   style="width:30px;padding:8px;"
        ></el-button>
      </template>
    </el-table-column>
    <el-table-column v-for="column in show_columns" :key="column" :label="column"
                     align="center">
      <template v-slot="scope">
        <span v-if="isTrue(scope.row[column])">✅</span>
        <span v-else-if="isFalse(scope.row[column])">🚫</span>
        <el-tag v-else-if="needTag(column, scope.row[column])">
          {{ displayTag(scope.row[column]) }}
        </el-tag>
        <div v-else-if="column === '_id' || column == 'id' || column =='name' " class="strong">
          {{ scope.row[column] }}
        </div>
        <template v-else>{{ suit(display(scope.row[column])) }}</template>

      </template>
    </el-table-column>
    <el-table-column width="80" align="center">
      <template v-slot="scope">
        <el-button type="warning" plain round @click="delete_click(scope.row)" size="small">
          删除
        </el-button>
      </template>
    </el-table-column>

    <template #head="scope">
      <el-dialog :title="$data.title" v-model="$data.dlg_show" width="80vw" :close-on-click-modal="true">
        <preview-json-row :model-value="$data.row"></preview-json-row>
      </el-dialog>

      <el-dialog title="设置显示列" v-model="$data.view_dlg" width="80vw"
                 :close-on-click-modal="true">

        <kv label="显示列">
          <el-tag disable-transitions v-for="c in show_columns" :key="c" @click="$data.excludes.push(c)">{{ c }}
          </el-tag>
        </kv>

        <kv label="隐藏列">
          <el-tag disable-transitions type="warning" v-for="c in $data.excludes" @click="$data.excludes.removeItem(c)"
                  :key="c">{{ c }}
          </el-tag>
        </kv>


        <el-button @click="show_ok_click">确定</el-button>
      </el-dialog>
    </template>
  </my-list>
</template>
<script setup>
/**
 * Created by CodeGenerator at 2021-04-13 19:37:26
 */
import previewJsonRow from "./preview-json-row.vue"
import {Setting, CirclePlus, Remove, CaretBottom, CaretTop, View} from '@element-plus/icons-vue'


defineOptions({
  name: "preview-json-table",
  inheritAttrs: true,
});

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();


//定义data
const $data = reactive({
  "pageNumber": 1,
  "version": 0,
  "dlg_show": false,
  "previewData": {},
  "row": {},
  "view_dlg": false,
  "title": "",
  "excludes": [],
  "columns": []
});


const $props = defineProps({
  currentPage: {type: Number}
});


const $model = defineModel({type: Object});


const list = ref();

//定义事件
const $emit = defineEmits(["update:currentPage", "pager-change", "delete"]);

const show_columns = $computed(function () {
  var timeColumns = $data.columns.filter(it =>
      it.includes("Date") ||
      it.includes("date") ||
      it.includes("Time") ||
      it.includes("time") ||
      it.includes("At")
  )
  if ($data.columns.length > 8 && !$data.excludes.length) {
    $data.excludes.addAll(timeColumns);
  }
  return $data.columns.minus($data.excludes);
});

const view_open_click = function () {
  $data.view_dlg = true;
};
const show_ok_click = function () {
  $data.view_dlg = false;
  jv.$saveData("excludes", $data.excludes);
  $data.version = Date.now()
};
const setTitle = function () {
  var set = [];
  if ($data.row.id) {
    set.push($data.row.id)
  }
  if ($data.row.name) {
    set.push($data.row.name)
  }
  $data.title = set.filter(it => it).join(" : ")
};
const analyse = function () {
  var previewData = $model.value;
  if (!previewData || !previewData.data) {
    return;
  }
  var cs = new Set();
  previewData.data.forEach(row => {
    Object.keys(row).forEach(column => {
      var value = row[column];
      if (jv.isNull(value)) {
        return;
      }
      var valueType = value.getJsType();
      if (valueType == "object" || valueType == "function") {
        return;
      }
      if (valueType == "array" && !value.length) {
        return;
      }
      if (valueType == "string" && !value) {
        return;
      }

      cs.add(column);
    })
  });
  var cs2 = [];
  cs2.addAll(cs);
  $data.columns = cs2.sort(jv.getKeySorter());
  $data.version = Date.now()
};
const needTag = function (c, v) {
  if (jv.isNull(v)) return false;
  var type = v.getJsType();
  if (type == "array") {
    return true;
  }
  if (v === "true" || v === "false" || type == "boolean") {
    return true;
  }
};


const isTrue = v => {
  if (jv.isNull(v)) {
    return false;
  }
  if (v === true) return true;
  var str = v.toString();
  if (str.length > 4) {
    return false;
  }
  return str.toLowerCase() == "true";
}

const isFalse = v => {
  if (jv.isNull(v)) {
    return false;
  }
  if (v === false) return true;
  var str = v.toString();
  if (str.length > 5) {
    return false;
  }
  return str.toLowerCase() == "false";
}


const displayTag = function (v) {
  if (jv.isNull(v)) return v;
  var type = v.getJsType();
  if (type == "array") {
    return v.length;
  }
  return v;
};
const row_click = function (row) {
  $data.row = row;
  $data.dlg_show = true;
  setTitle();
};
const delete_click = function (row) {
  var rowId = row._id || row.id;
  var rowName = row.name || rowId;
  jv.confirm('确认删除 ' + rowName + ' 吗？').then(res => {
    $emit("delete", row);
  });
};


const display = function (obj) {
  if (!obj) return obj;

  var type = obj.getJsType();
  if (type == "string") {
    return obj;
  }
  if (type == "number") {
    return obj;
  }

  if (type == "array") {
    return "[" + obj.length + "]"
  }

  if (type === "boolean") {
    return obj;
  }

  return JSON.stringify(obj);
}

const suit = function (v) {
  if (!v) return v;
  var len = v.length;
  if (jv.isNull(len)) {
    return v;
  }
  if (len < 50) return v;
  if (!v.slice) {
    return v;
  }
  return v.slice(0, 47) + " ...";
}

watch($model, v => {
  $data.previewData = v;
  analyse();
}, {immediate: true})

watch(() => $props.currentPage, v => {
  if ($data.pageNumber != v) {
    $data.pageNumber = v;
  }
}, {immediate: true})

watch(() => $data.pageNumber, v => {
  $emit("update:currentPage", v);
}, {immediate: true})


onMounted(() => {
  jv.$loadData("excludes", v => $data.excludes = v);
  analyse();
})

</script>

<style lang="scss" scoped>
.strong {
  background-color: #5a22ff;
  color: white;
  zoom: 1.02;
  border-radius: 6px;
  padding: 2px 4px;
  display: inline-block;
}

/*productline*/
.pl {
  border-bottom: solid 1px gray;
  margin: 8px;
  display: inline-block;
  padding: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  border-radius: 10px;
  position: relative;
  z-index: 9;
}

/*title*/
.ti {
  font-weight: bold;
  margin: 4px;
  display: inline-block;
  border-radius: 8px;
  background-color: darkblue;
  padding: 2px 5px;
  color: white;
}

.row {
  display: block;
  font-size: small;
  margin-left: 16px;
}

.pl:before {
  content: " ";
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  opacity: 0.3;
  border-radius: 10px;
  z-index: -999;
}

.pl:nth-of-type(5n+1):before {
  background-color: #75f0fc;
}

.pl:nth-of-type(5n+2):before {
  background-color: #fdeeaa;
}

.pl:nth-of-type(5n+3):before {
  background-color: #b5b3ff;
}

.pl:nth-of-type(5n+4):before {
  background-color: #8cfec0;
}

.pl:nth-of-type(5n):before {
  background-color: #feb9bd;
}

a {
  background-color: #485385;
  padding: 0 4px;
  margin: 2px 4px;
  color: white;
  display: inline-block;
  border-radius: 5px;
  text-decoration: none;
  zoom: 1.02;
}

</style>